const express = require('express');
const app = express();

// cookie
const cookieParser = require('cookie-parser');
app.use(cookieParser());

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

const mongoose = require('mongoose');
require("./model_chat.js");
const Chat = mongoose.model("chatSchema");

const server = require('http').Server(app);
const io = require('socket.io')(server);

io.on('connection',(socket)=>{
    console.log("sokect连接成功")
    // 监听前端发送过来的数据
    socket.on('send_msg',(data)=>{
        const { from ,to, chat } = data;
        const chat_id = [from,to].sort().join('_');
        Chat.create({chat_id,from,to,chat},(err,data)=>{
            // 有数据，主动emit发送
            io.emit('res_msg',Object.assign({},data._doc));
        })
    })
})
/**
 * 连接数据库
 */
// 方式1
// const mongoose = require('mongoose');
// mongoose.connect('mongodb://localhost:27017/advertise');
// mongoose.connection.on('open',(err)=>{
//     console.log('连接成功')
// })
// 方式二
require('./model.js');

/**
 * 配置跨域
 */
app.all('*',function(req, res, next) {
    //需要显式设置来源,不能写*
    res.header("Access-Control-Allow-Origin", 'http://localhost:3000');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("Access-Control-Allow-Credentials",true);
    //带cookies
    res.header("Content-Type", "application/json;charset=utf-8");
   next();
});


const userRouter = require('./api_user');
// 使用中间件(中间件是路由的话，第一个参数是路由)
// '/userapi'-》，和其前缀相关的子路由是userRouter来定义
app.use('/userapi',userRouter);

const chatRouter = require('./api_chat');
app.use('/chatapi',chatRouter);


server.listen(3001,()=>{

})